
package com.netease.xone.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import protocol.XoneCallBack;
import protocol.XoneService;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.netease.image.ImageType;
import com.netease.share.ShareBind;
import com.netease.share.ShareType;
import com.netease.share.db.ManagerShareBind;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityWBBind;
import com.netease.xone.app.XoneApp;
import com.netease.xone.widget.LoadingImageView;

import db.manager.ManagerAccount;

public class FragmentWBList extends FragmentBase {

    private static final String TAG = "FragmentWBList";

    public static final int REQUEST_CODE_FOR_WHETHER_BIND_SUCCESS = 111;

    private ListView mListView;

    private Cursor mCursor = null;

    private ContentObserver mObserver;

    private ShareBind mCurrentItem;

    private WBListAdapter mAdapter;

    private ProgressDialog mWaitingDialog;

    private boolean mIsSinaBound;

    private boolean mFirstLoad = true;


    private String mUserKey;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mUserKey = ManagerAccount.getInstance().getCurrentAccountName();
        mCursor = ManagerShareBind.getAllValidShareBind(mUserKey);
        mObserver = new WBContentObserver(new Handler());
        mCursor.registerContentObserver(mObserver);
        XoneService.getInstance().addListener(mXoneCallBack);
        XoneService.getInstance().doSyncBindingInfo(mUserKey);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wb_list, container, false);
        findViews(view);
        getActivity().setTitle(R.string.setting_item_share);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        mUserKey = ManagerAccount.getInstance().getCurrentAccountName();
        updateData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mCursor != null) {
            // mCursor.unregisterContentObserver(mObserver);
            mCursor.close();
        }
        mAdapter = null;
        XoneService.getInstance().removeListener(mXoneCallBack);

    }

    private static final int DIALOG_BOUND = 1;

    // TODO add field to mark which account
    void on2UnboundAccount() {
        if (mCurrentItem != null) {
            try {
//                ManagerShareBind.removeShareBind(mUserKey, mCurrentItem.getShareType());
                mCurrentItem.setState(-1);
                mCurrentItem.setBindTime(System.currentTimeMillis());
                ManagerShareBind.updateShareBind(mUserKey, mCurrentItem);
                clearCookie();
                showToast(getString(R.string.unbound_success)
                        + weiboTypeToString(mCurrentItem.getShareType()));
//                updateData();
                XoneService.getInstance().doSyncBindingInfo(mUserKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String weiboTypeToString(ShareType type) {
        switch (type) {
            case Netease:
                return getString(R.string.weibo_type_netease_name_text);
            case Sina:
                return getString(R.string.weibo_type_sina_name_text);
            case Qqmblog:
                return getString(R.string.weibo_type_tencent_name_text);
            case Renren:
                return getString(R.string.weibo_type_renren_name_text);
            case Tencent:
                return getString(R.string.weibo_type_qzone_name_text);
        }
        return null;
    }

    private void clearCookie() {
        CookieSyncManager.createInstance(getActivity().getApplicationContext());
        CookieManager.getInstance().removeAllCookie();
        CookieSyncManager.getInstance().sync();
    }

    class WBContentObserver extends ContentObserver {

        public WBContentObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            if (mCursor != null && !mCursor.isClosed()) {
                mCursor.close();
                mCursor = ManagerShareBind.getAllValidShareBind(mUserKey);
            }
            updateData();
            super.onChange(selfChange);
        }
    }

    ShareType[] mShareTypes = new ShareType[] {
            ShareType.Netease, ShareType.Sina, ShareType.Qqmblog, ShareType.Renren,
            ShareType.Tencent
    };

    void updateData() {
        // mCursor.requery();
        if (mCursor != null) {
            mCursor.close();
        }
        mCursor = ManagerShareBind.getAllValidShareBind(mUserKey);

        Map<ShareType, ShareBind> map = new HashMap<ShareType, ShareBind>();
        if (mCursor.moveToFirst()) {
            do {
                ShareBind shareBind = new ShareBind(mCursor, ShareBind.CURSOR_TYPE_DEFAULT);
                map.put(shareBind.getShareType(), shareBind);
            } while (mCursor.moveToNext());
        }

        List<ShareBind> data = new ArrayList<ShareBind>();

        for (ShareType type : mShareTypes) {
            ShareBind shareBind = map.get(type);
            if (shareBind == null) {
                shareBind = new ShareBind(type, false);
                shareBind.setName(getString(R.string.weibo_un_setting_text));

            }

            data.add(shareBind);
        }

        mAdapter = new WBListAdapter(getActivity());
        mListView.setAdapter(mAdapter);
        mAdapter.setData(data);
        mAdapter.notifyDataSetChanged();

    }

    void findViews(View view) {
        mListView = (ListView)view.findViewById(R.id.wb_list);
        // mListView.setDivider(getResources().getDrawable(R.drawable.line1));
//        updateData();

    }

    class WBListAdapter extends BaseAdapter {

        List<ShareBind> mData = new ArrayList<ShareBind>();

        Context mContext;

        @Override
        public boolean isEnabled(int position) {
            return false;
        }

        public void setData(List<ShareBind> data) {
            mData.clear();
            mData.addAll(data);
        }

        public WBListAdapter(Context context) {
            mContext = context;
        }

        @Override
        public int getCount() {
            return mShareTypes.length;
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                View mView = LayoutInflater.from(mContext).inflate(R.layout.view_wblist_item, null);
                ViewHolder holder = new ViewHolder();
                holder.mPortrait = (LoadingImageView)mView.findViewById(R.id.header_portrait);
                holder.mWeiboName = (TextView)mView.findViewById(R.id.weibo_name);
                holder.mUserName = (TextView)mView.findViewById(R.id.username);
                holder.mLoginLogout = (TextView)mView.findViewById(R.id.login_logout);
                holder.mIsLogin = (TextView)mView.findViewById(R.id.isLogin);
                mView.setTag(holder);
                convertView = mView;
            }

            final ViewHolder holder = (ViewHolder)convertView.getTag();

            final ShareBind item = (ShareBind)getItem(position);

            holder.mLoginLogout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (item.isBind()) {
                        onUnboundButtonClick(item);
                    } else {
                        if(XoneApp.getAppInstance().isLoginUser(getActivity())){
                            onBoundButtonClick(item);
                        }
                    }
                }
            });

           
            if (item.isBind()) {
                holder.mPortrait.setBackgroundResource(R.drawable.avatar_user_default_50);
                 if(!TextUtils.isEmpty(item.getProfile())) {
                     int size = getResources().getDimensionPixelSize(R.dimen.padding_60);
                     int roundSize = getResources().getDimensionPixelSize(R.dimen.common_avatar_rounder);
                     holder.mPortrait.setServerClipSize(size, size);
                     holder.mPortrait.setLoadingImage(item.getProfile(),ImageType.RoundMemCache,roundSize);
                 } 
                holder.mWeiboName.setText(item.getName());
                holder.mIsLogin.setVisibility(View.GONE);
                holder.mUserName.setVisibility(View.VISIBLE);
                holder.mUserName.setText(item.getDomainUrl());
                holder.mLoginLogout.setText(R.string.weibo_unbound_text);
                holder.mLoginLogout.setTextColor(getResources().getColor(R.color.button_gray));
                holder.mLoginLogout.setBackgroundResource(R.drawable.selector_gray_btn);
            } else {
                int textResId = -1;
                int drawableId = -1;
                switch (item.getShareType()) {
                    case Netease:
                        textResId = R.string.weibo_type_netease_name_text;
                        drawableId = R.drawable.logo_163weibo;
                        break;
                    case Sina:
                        textResId = R.string.weibo_type_sina_name_text;
                        drawableId = R.drawable.logo_weibo;
                        break;
                    case Qqmblog:
                        textResId = R.string.weibo_type_tencent_name_text;
                        drawableId = R.drawable.logo_txweibo;
                        break;
                    case Renren:
                        textResId = R.string.weibo_type_renren_name_text;
                        drawableId = R.drawable.logo_renren;
                        break;
                    case Tencent:
                        textResId = R.string.weibo_type_qzone_name_text;
                        drawableId = R.drawable.logo_qqspace;
                        break;
                    default:
                        break;
                }
                holder.mWeiboName.setText(textResId);
                holder.mUserName.setVisibility(View.GONE);
                holder.mPortrait.setImageResource(drawableId);
                holder.mIsLogin.setVisibility(View.VISIBLE);
                holder.mIsLogin.setText(R.string.not_logged_in);
                holder.mLoginLogout.setText(R.string.weibo_bound_text);
                holder.mLoginLogout.setTextColor(getResources().getColor(R.color.white));
                holder.mLoginLogout.setBackgroundResource(R.drawable.selector_blue_btn);
            }

            return convertView;
        }
    }

    void onBoundButtonClick(ShareBind item) {
        mCurrentItem = item;
        ActivityWBBind.launch(getActivity(), item.getShareType().value());
    }

    void onUnboundButtonClick(ShareBind item) {
        mCurrentItem = item;

        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.unbound_dlg_title_text)
                .setMessage(R.string.unbound_dlg_message_text)
                .setPositiveButton(R.string.unbound_dlg_positive_btn_text,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mIsSinaBound = false;
                                on2UnboundAccount();
                            }
                        })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
    }

    // private class WBAccount {
    // String mName;
    // long mID;
    // ShareType mType;
    // boolean mStatus = false;
    // String mMainUrl;
    // String mPortrait;
    // }

    static class ViewHolder {

        LoadingImageView mPortrait;

        TextView mWeiboName;

        TextView mUserName;

        TextView mLoginLogout;

        TextView mIsLogin;
    }
    private XoneCallBack mXoneCallBack = new XoneCallBack() {
        @Override
        public void onBindingAccSync(int transactionId) {
            updateData();
        };
    };
}
